package gui;

import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

import dbConnection.Database;

public class LoginScreen extends JPanel {

    //reference to database
    private Database DB;
    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    public LoginScreen(final MainScreen app, Database dB2) {
	
		this.DB = dB2;
		final JLabel userNameLabel = new JLabel("username");
		final JTextField userName = new JTextField();
		final JLabel passwordLabel = new JLabel("password");
		final JPasswordField password = new JPasswordField();
		final JButton login = new JButton("Login");
		
		userNameLabel.setMaximumSize(new Dimension(100,30));
		userNameLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
		userName.setMaximumSize(new Dimension(100,30));
		userName.setAlignmentX(Component.CENTER_ALIGNMENT);
		passwordLabel.setMaximumSize(new Dimension(100,30));
		passwordLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
		password.setMaximumSize(new Dimension(100,30));
		password.setAlignmentX(Component.CENTER_ALIGNMENT);
	
		//add enter listeners so you can click enter anywhere in the gui
		EnterListener loginListener = new EnterListener(login);
		userName.addActionListener(loginListener);
		password.addActionListener(loginListener);
	
		login.addActionListener(new ActionListener() {
	    	@Override
	    	public void actionPerformed(ActionEvent arg0) {
	    	    String userPassword = new String(password.getPassword());
	    	    if (userName.getText().equals("Admin") && userPassword.equals("root")) {
	    	    	app.showAdminView();
	    	    } else  {
	    	    	if(DB.con != null) {
	    				Statement statement = null;	  
	    				try {
	    					statement = DB.con.createStatement();
	
	    					ResultSet resultSet = statement.executeQuery("SELECT userID FROM user WHERE name = '" + 
	    					userName.getText() + "' AND password = '" + userPassword + "'"
	    					);
	    					if (resultSet != null && resultSet.next()) {
	    						app.showUserView(resultSet.getInt(1));
	    					}
	    				} catch (SQLException e) {
	    					// continue
	    				}
	    	    	}
	    	    	
	    		userName.setText("");
	    		password.setText("");
	    	    }
	    	    
	    	}
		});
		
		//add doodads
		setMinimumSize(new Dimension(100,200));
		//setMaximumSize(new Dimension(200,500));
		setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
		add(userNameLabel);
		add(userName);
		add(passwordLabel);
		add(password);
		add(login);
	    }
	}
